#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include "cJSON.h"

#define JSON_FILE "test.js"

#define SAFE_FREE(_p)	do {\
		if ((_p) != NULL) {\
			free(_p);\
			(_p) = NULL;\
		}\
	} while (0)


#define SAFE_DELETE_ARRAY(_arr) do {\
				if ( (_arr) != NULL ) {\
					delete [] (_arr);\
					(_arr) = NULL;\
				}\
			} while (0)


#define STR_EMPTY(_str)		( (_str) == NULL || (_str)[0] == '\0' )

int get_content(char *content, int len)
{
    FILE *f = fopen(JSON_FILE, "r");
    if (f == NULL)
    {
        return -1;
    }
    
    len = fread(content, 1, len, f);
    fclose(f);
    f = NULL;
    
    return len;
}


int main()
{
    char json[2048] = { 0 };
    get_content(json, sizeof(json));
    printf("json: %s\n", json);
    
    cJSON *root = NULL;
    cJSON *item = NULL;

    root = cJSON_Parse(json);     
    if (root == NULL) 
    {
        printf("Error before: [%s]\n", cJSON_GetErrorPtr());
        return -1;
    }
    printf("-------------------------------------------\n");
    item = cJSON_GetObjectItem(root, "ErrNo");
    if (item != NULL)
    {
        printf("Key: %s, Value: %d\n", item->string, item->valueint);
    }
    printf("-------------------------------------------\n");
    item = cJSON_GetObjectItem(root, "Function");
    if (item != NULL)
    {
        printf("string: %s\n", item->string);    
        printf("valuestring: %s\n", item->valuestring);
    }
    else
    {
        printf("Error before: [%s]\n", cJSON_GetErrorPtr());
    }
    printf("-------------------------------------------\n");
    item = cJSON_GetObjectItem(root, "Virus");
    if (item != NULL)
    {
        printf("string: %s\n", item->string);    
    }
    else
    {
        printf("Error before: [%s]\n", cJSON_GetErrorPtr());
    }
    printf("--------------------array------------------\n");
    // 获取Virus中的内容
    cJSON *virus = item;
    int arr_size = cJSON_GetArraySize(virus);
    cJSON *first_item = virus->child;
    for(int i = 0;i < arr_size; ++i)
    {
        printf("--------------------array[%d]------------------\n", i);
        printf("VirusPath: %s\n", cJSON_GetObjectItem(first_item, "VirusPath")->valuestring);
        printf("VirusName: %s\n", cJSON_GetObjectItem(first_item, "VirusName")->valuestring);
        printf("FileMD5: %s\n", cJSON_GetObjectItem(first_item, "FileMD5")->valuestring);
        
        first_item = first_item->next; // 下一个子对象
    }
    cJSON_Delete(root);
    
    return 0;
}